<?php
namespace Admin\Model;
use Think\Model;
class ContractModel extends Model {
	const STATE_CANCEL = -1;//合同取消
	const STATE_NEED_AUTH = 0;//待审核
	const STATE_SERVICE = 1;  // 服务中
	const STATE_INVALID = 2;//升级作废
	const STATE_END = 3; //到期
	const STATE_SIGNING = 4; //签订中

	//合同的具体签订状态
	const SIGN_NO = 0;//合同未签订
	const SIGN_OK = 10; //合同签订完成

	//违规状态
	const WEIGUI_STATUS_UNKNOWN = 0;//未知
	const WEIGUI_STATUS_NEDD_EXPORT = 11; //违规未导出
	const WEIGUI_STATUS_EXPORTED = 12; //违规已经导出
	const WEIGUi_STATUS_NO = 21; //不违规

	static $basical=array(0=>'零','壹','贰','叁','肆','伍','陆','柒','捌','玖');	
 	static $advanced=array(1=>'拾','佰','仟');
	//编辑合同信息
	public function editor($arr){

		$where['contract_id']     = $arr['contract_id'];

		$map['state'] = $arr['state'] ;
		$map['end_time']          = $arr['end_time'];
		$map['is_need_combine']   = $arr['is_need_combine'];
		$map['is_refund']         = $arr['is_refund'];
		$map['mount']             = $arr['mount'];
		$map['need_return_visit'] = $arr['need_return_visit'];
		$map['product_id']        = $arr['product'];
		$map['sign_status']       = $arr['sign_status'];
		$map['remark']            = $arr['remark'];
		$map['start_time']        = $arr['start_time'];
		$map['weigui_status']     = $arr['weigui_status'];
		$map['create_time']       = date("Y-m-d H-i-s");

		$map['second_party_name']    = $arr['second_party_name'];
		$map['second_party_email']   = $arr['second_party_email'];
		$map['second_party_phone']   = $arr['second_party_phone'];
		$map['second_party_idcard']  = $arr['second_party_idcard'];
		$map['second_party_address'] = $arr['second_party_address'];

		$map['title']                = $arr['title'];
		$map['first_party_name']     = $arr['first_party_name'];
		$map['first_party_address']  = $arr['first_party_address'];
		$map['first_party_bank_account'] = $arr['first_party_bank_account'];
		$map['first_party_bank_deposit'] = $arr['first_party_bank_deposit'];

		$map['survey_code'] = isset($arr['survey_code']) ? $arr['survey_code']:'';
		#根据提交的产品更新合同绑定的投顾老师以及证书 
		$MUser  = D('Admin/User');
		$whereu = array();
		$whereu['p.product_id'] = array('eq', $map['product_id']);
		$dataTeacher = $MUser->alias('u')
												 ->field("u.teacher_name,u.cert_num")
												 ->join("LEFT JOIN product p on p.manager_id=u.user_id")
												 ->where( $whereu )
												 ->find();
		if ($dataTeacher){
			$map['teacher_name'] = $dataTeacher['teacher_name'];
			$map['teacher_cert'] = $dataTeacher['cert_num'];
		}

		$contract = M("contract")->where($where)->save($map);
		if($contract){
			// $wheres['payrecord_id']= $arr['payrecord_id'];
			// $maps['pay_mount']     = $arr['mount'];
			// $maps['create_time']   = date("Y-m-d H-i-s");
			// $payrecord = M("pay_record")->where($wheres)->save($maps);
			$res['rcode'] = 1;
		}else{
			$res['msg']   = "编辑信息失败!!!";
		}
		return $res;
	}
	//合同合并
	public function merge_editor($arr){
		foreach ($arr['checkbox']as $key => $value) {
			if($value != $arr['main']['contract_id']){
				$where['contract_id']   = $value;
				$map['state']           = 2;
			 	$map['merge_to']        = $arr['main']['contract_id'];
			 	$map['is_need_combine'] = 0;
				$list = M('contract')->where($where)->save($map);
				if($list){	
					$where['record_status'] = 1;
					$payrecord[$key][] = M("pay_record")->where($where)->select();
				}
			}else{
				$where['contract_id']   = $arr['main']['contract_id'];
				$maps['start_time']      = $arr['stime'];
				$maps['end_time']        = $arr['etime'];
				$maps['product_id']      = $arr['product'];
				$maps['mount']           = $arr['mount'];
				$maps['is_refund']       = 0;   
				$maps['type']            = 0;
				$maps['sign_status']     = 0;	
				$maps['weigui_status']   = 0;
				$maps['state']           = 0;
				$maps['is_delete']       = 0;
				$maps['need_return_visit'] = 0; 
				$maps['merge_to']        = '';
				$maps['create_time']     = date("Y-m-d H-i-s");
				
				$wheres['customer_id']   = array('eq',$arr['main']['customer_id']);
				$wheres['contract_id']   = array('neq',$val);
				$wheres['is_delete']     = array('eq','0');
				$wheres['state']         = array(array('neq','2'),array('neq','-1'),'and');
				$find = M("contract")->where($wheres)->find();
				if(!empty($find) && $find){
					$maps['is_need_combine'] = 1;
				}else{
					$maps['is_need_combine'] = 0;
				}
				$result = M('contract')->where($where)->save($maps);
			}
		}
		if($result){
			foreach ($payrecord as $k => $val) {
				if(!empty($val)){
					foreach ($val as $v => $child) {
						if(!empty($child)){
							foreach ($child as $r => $subset) {
								$new[] = $subset;
							}
						}
					}
				}
			}
			foreach ($new as $s => $copy) {

				$pays['pay_mount']    = $copy['pay_mount'];
				$pays['refund_mount'] = $copy['refund_mount'];
				$pays['invoice_mount']= $copy['invoice_mount'];
				$pays['pay_name']     = $copy['pay_name'];
				$pays['pay_way']      = $copy['pay_way'];
				//---------
				$pays['pay_order']    = $copy['pay_order'];
			 	$pays['pay_time']     = $copy['pay_time'];
			 	$pays['pay_type']     = $copy['pay_type'];
			 	$pays['xufei_type']   = $copy['xufei_type'];		
			 	$pays['record_status']= $copy['record_status'];
		 		//----------
			 	$pays['remark']       = $copy['remark'];
			 	$pays['create_time']  = $copy['create_time'];
			 	$pays['auditor']      = $copy['auditor'];
			 	$pays['audit_sector'] = $copy['audit_sector'];
			 	$pays['audit_role']   = $copy['audit_role'];
			 	//----------
			 	$pays['audit_time']   = $copy['audit_time'];
			 	$pays['audit_msg']    = $copy['audit_msg'];
			 	$pays['audit_res']    = $copy['audit_res'];
			 	$pays['creator']      = $copy['creator'];
			 	$pays['creator_sector'] = $copy['creator_sector'];
			 	//----------
			 	$pays['customer_id']    = $copy['customer_id'];
			 	$pays['contract_id']    = $arr['main']['contract_id'];
			 	$pays['customer_name']  = $copy['customer_name'];
			 	$pays['customer_weixin_id']       = $copy['customer_weixin_id'];
			 	$pays['customer_weixin_nickname'] = $copy['customer_weixin_nickname'];
			 	//----------
			 	$pays['customer_sex']        = $copy['customer_sex'];
			 	$pays['customer_phone']      = $copy['customer_phone'];
			 	$pays['customer_address']    = $copy['customer_address'];
			 	$pays['customer_qq']         = $copy['customer_qq'];
			 	$pays['customer_location']   = $copy['customer_location'];
			 	//----------
			 	$pays['customer_career']     = $copy['customer_career'];
			 	$pays['customer_education']  = $copy['customer_education'];
			 	$pays['customer_birth']      = $copy['customer_birth'];
			 	$pays['customer_mount']      = $copy['customer_mount'];
			 	$pays['customer_product']    = $copy['customer_product'];
			 	//----------
			 	$pays['customer_price']      = $copy['customer_price'];
			 	$pays['customer_buycount']   = $copy['customer_buycount'];
			 	$pays['contract_start_time'] = $copy['contract_start_time'];
			 	$pays['customer_sales']      = $copy['customer_sales'];
			 	$pays['customer_source']     = $copy['customer_source'];
			 	//----------
			 	$pays['customer_remark']     = $copy['customer_remark'];
			 	$pays['is_export']           = $copy['is_export'];
			 	$pays['is_conflict']         = $copy['is_conflict'];
			 	$pays['excel_order']         = $copy['excel_order'];
			 	$pays['sales_manager']       = $copy['sales_manager'];

			 	$pays['sales_person']        = $copy['sales_person'];
			 	$pays['sales_sector']        = $copy['sales_sector'];
			 	$pays['sales_sub_company']   = $copy['sales_sub_company'];
			 	$pays['pay_id']              = $copy['pay_id'];
			 	
			 	$resultAdd = M("pay_record")->add($pays);
			 	if($resultAdd){
			 		$save_where['payrecord_id'] = $copy['payrecord_id'];
			 		$save_state['record_status'] = 2;
			 		$pay_record = M("pay_record")->where($save_where)->save($save_state);
			 	}
			}
		}
		if($pay_record) $res['rcode'] = 1;
		else $res['rcode'] = 2;
		
		return $res;
	}
	//人民币转换
	public static function ParseNumber($number){
	    $number=trim($number);
	    if(!is_numeric($number)||intval($number)>999999999999) return 'error';
	    if($number==0) return '零';
	    if(strpos($number,'.')){
	      $number=round($number,2);
	      $data=explode('.',$number);
	      $data[0]=self::int($data[0]);
	      $data[1]=self::dec($data[1]);
	      return $data[0].$data[1];
	    }else{
	      return self::int($number).' '.'整';
	    }
  	}
  	public static function int($number){
	    $arr=array_reverse(str_split($number));
	    $data='';
	    $zero=false;
	    $zero_num=0;
	    foreach($arr as $k=>$v){
	      $_chinese='';
	      $zero=($v==0)?true:false;
	      $x=$k%4;
	      if($x && $zero && $zero_num>1)continue;
	      switch($x){
	        case 0:
	          if($zero){
	            $zero_num=0;
	          }else{
	            $_chinese=self::$basical[$v];
	            $zero_num=1;
	          }
	          if($k==8){
	            $_chinese.='亿';
	          }elseif($k==4){
	            $_chinese.='万';
	          }
	          break; 
	        default:
	          if($zero){
	            if($zero_num==1){
	              $_chinese=self::$basical[$v];
	              $zero_num++;
	            }
	          }else{
	            $_chinese=self::$basical[$v];
	            $_chinese.=self::$advanced[$x];
	          }
	      }
	      $data=$_chinese.$data;
	    }
	    return $data.'元';
  	}
  	public static function dec($number){
	    if(strlen($number)<2) $number.='0';
	    $arr=array_reverse(str_split($number));
	    $data='';
	    $zero_num=false;
	    foreach($arr as $k=>$v){
	      $zero=($v==0)?true:false;
	      $_chinese='';
	      if($k==0){
	        if(!$zero){
	          $_chinese=self::$basical[$v];
	          $_chinese.='分';
	          $zero_num=true;
	        }
	      }else{
	        if($zero){
	          if($zero_num){
	            $_chinese=self::$basical[$v];
	          }
	        }else{
	          $_chinese=self::$basical[$v];
	          $_chinese.='角';
	        }
	      }
	      $data=$_chinese.$data;
	    }
	    return $data;
	}

	public function User(){
		$uinfo = UserModel::loadFromSession();
		return $uinfo ;
	}
}